# -*- coding: utf-8 -*-
# @Time :
# @Author : RLH
# @File :
# 功能描述: API数据交互中心
# 说明：
# 启动程序后，先运行API_BluePrint蓝图中的add_url_rule_func()函数，将数据库中的URL动态加载注册到蓝图中
# 新增接口后，无法动态加载，使用mock_response函数，临时获取接口响应。待重新系统后，重新加载接口

from flask import Blueprint, render_template,request, jsonify
from core.Operation_DB.SqlLite_DB import sqliteDatabase


# 将python2的编码格式改为utf-8
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')



API_BluePrint = Blueprint('API_BluePrint', __name__, template_folder="templates", static_folder="response_file")





def Api_interface_func():
    """
    模拟接口返回
    :return:  json报文
    """

    endpoint = request.endpoint
    api_name = endpoint.split('.')[1]
    data = {"resultCode": "99", "resultDesc": "请求有误，未定义{0}接口".format(api_name)}
    db = sqliteDatabase()
    sql = 'select * from api_data where api_name=?'
    value = (api_name,)
    api_data = list(db.select_SQL(sql, value)[0])
    # time.sleep(10)
    if not api_data:
        return data
    else:
        return render_template(api_data[3])



def add_url_rule_func():
    db = sqliteDatabase()
    sql = 'select  api_name, url_path from api_data;'

    sql_data_lis = db.select_SQL(sql)
    db.close()
    for sql_data in sql_data_lis:
        API_BluePrint.add_url_rule(sql_data[1], endpoint=sql_data[0], methods=['GET', 'POST', 'OPTIONS'], view_func=Api_interface_func)
#

add_url_rule_func()


# 动态路由处理 - 捕获所有路径
@API_BluePrint.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def mock_response(path):
    db = sqliteDatabase()
    # 添加前导斜杠以标准化路径
    if not path.startswith('/'):
        path = '/' + path
    sql = f'select  api_name, url_path, template from api_data where url_path="{path}";'
    endpoint = db.select_SQL(sql)
    db.close()
    if endpoint:
        return render_template(endpoint[0][2])
    else:
        # 如果没有找到注册的端点，返回404
        return jsonify({
            "error": f"Endpoint {path} not found",
            "message": "This endpoint is not registered in the mock server"
        }), 404



